<template>
  <el-card style="width: 280px;">
    <el-form label-width="80px" size="small">
      <el-upload
          class="avatar-uploader"
          action="http://localhost:8081/file/upload"
          :show-file-list="true"
          :on-success="handleAvatarSuccess"
      >
        <img v-if="user.avatarUrl" :src="user.avatarUrl" class="avatar">
        <i v-else class="el-icon-plus avatar-uploader-icon"></i>
        <div class="el-upload__tip" slot="tip">只能上传jpg/png文件，且不超过500kb</div>
      </el-upload>
      <el-form-item>
        <el-button type="primary" @click="upload">点击上传</el-button>
      </el-form-item>
    </el-form>
  </el-card>
</template>

<script>
export default {
  name: "Person",
  data() {
    return {
      user: localStorage.getItem("user") ? JSON.parse(localStorage.getItem("user")) : {},
      updateUser: ''
    }
  },
  methods: {
    handleAvatarSuccess(res) {
      this.user.avatarUrl = res
      this.updateUser = this.user
      localStorage.setItem("user", JSON.stringify(this.updateUser))
    },
    upload() {
      if(this.user.avatarUrl === null) {
        this.$message.error("请先上传文件")
      } else {
        this.request.post('/user/upload', this.user).then( res => {
          if(res.code === '200') {
            this.$message.success("上传成功")
            location.reload()
          }
        })
      }
    }
  }
}
</script>

<style>
.avatar-uploader {
  text-align: center;
  padding-bottom: 10px;
}
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 138px;
  height: 138px;
  line-height: 138px;
  text-align: center;
}
.avatar {
  width: 138px;
  height: 138px;
  display: block;
}
</style>